import axios, { AxiosRequestConfig } from "axios";
import qs from "qs";
// import store from '@/store'
import { showToast, showLoadingToast, showFailToast, closeToast } from "vant";
import { ContentTypeEnum } from "./httpEnum";
import router from "@/router";
import { useUserStroe } from "@/pinia/modules/main";
import { urlConfig } from "./extraConfig";
import crypto from "@/utils/encrypt/crypto.js";

//AES加密，做api健全
function generateSign(requestBody: any) {
  let timestamp = parseInt(Date.now() / 1000);
  let contentSign = "";
  for (const [k, v] of Object.entries(requestBody)) {
    // 暂时过滤掉value是对象的纯在
    const type = Object.prototype.toString.call(v);
    if (
      type !== "[object Object]" &&
      type !== "[object Array]" &&
      type !== "[object Map]"
    ) {
      contentSign += `${k}=${v}&`;
    }
  }
  contentSign += `timestamp=${timestamp}`;
  // console.log("---------str------------:", contentSign);
  // console.log("contentSign: ---", contentSign);
  // const sign = crypto.encrypt(contentSign);
  // const sign = crypto.aesEcbEncrypt(JSON.stringify(contentSign));
  const sign = crypto.aesEcbEncrypt(contentSign);
  // console.log("encrypt: ", sign);
  return { "JD-Signature": sign, "JD-Timestamp": timestamp };
}

console.log(import.meta.env);
// const VITE_APP_BASE_URL = "https://app.jindisc.com";
// create an axios instance
console.log("baseurl", import.meta.env.VITE_BASE_URL);
const service = axios.create({
  // baseURL: import.meta.env.VITE_APP_BASE_URL + "/api", // 设置基础 URL
  baseURL: import.meta.env.VITE_BASE_URL, // 设置基础 URL
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000, // request timeout
});
interface CustomAxiosRequestConfig extends AxiosRequestConfig {
  hideLoading?: boolean;
}

interface BaseResponse<T = any> {
  code: number;
  data: T;
  msg: string;
}

// request拦截器 request interceptor
service.interceptors.request.use(
  (config: CustomAxiosRequestConfig) => {
    // 不传递默认开启loading
    if (!config.hideLoading) {
      // loading
      showLoadingToast({
        message: "加载中...",
        forbidClick: true,
      });
    }
    config.headers["Authorization"] = "Basic aDU6aDVfc2VjcmV0";
    const userStore = useUserStroe();
    config.headers["token"] = userStore.token;
    config.headers["Blade-Auth"] = `Bearer ${userStore.token}`;
    // console.log("------", config.extra);
    // if (store.getters['user/token'] &&  config.headers) {
    //   config.headers['X-Token'] = store.getters['user/token']
    // }
    const contentType =
      config.headers?.["content-type"] || config.headers?.["Content-Type"];
    const data = config.data;
    const headerSignH5 = generateSign(data || {});
    Object.assign(config.headers, headerSignH5);
    if (config.method?.toLocaleUpperCase() == "POST" && data) {
      if (ContentTypeEnum.FORM_DATA == contentType) {
        const fd = new FormData();
        Object.keys(data).forEach((key) => fd.append(key, data[key]));
        config.data = fd;
      } else if (ContentTypeEnum.FORM_URLENCODED == contentType) {
        config.data = qs.stringify(config.data);
      }
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);
// respone拦截器
service.interceptors.response.use(
  (response) => {
    // console.log("response: ", response);
    const res = response.data;
    let url: string = response.config.url as string;
    let extra = urlConfig[url];
    if (extra && extra.loading === false) {
    } else {
      closeToast();
    }
    // console.log("url: ", url);
    // console.log("res", res);
    if (url == "appChannel/kaptcha") {
      return Promise.resolve(response);
    }
    if (url == "appChannel/saveClick") {
      return Promise.resolve(response);
    }
    if (res.code !== 200) {
      // 登录超时,重新登录
      if (res.code === 401) {
        // store.dispatch('FedLogOut').then(() => {
        //   location.reload()
        // })
        // router.replace("/error");
        showFailToast(res.msg || "登录超时,重新登录~");
      } else {
        if (response.config.url == "appChannel/saveRegister") {
          showFailToast("验证码错误");
        } else {
          if (extra && extra.error === false) {
            return Promise.resolve(response);
          } else {
            showFailToast(res.msg || "服务器访问出错了~");
          }
        }
      }
      return Promise.reject(res || "error");
    } else {
      return Promise.resolve(response);
    }
  },
  (error: Error) => {
    if (error.message?.includes("timeout")) {
      showToast("请求超时!");
    }
    console.log(`err${error}`); // for debug
    return Promise.reject(error);
  }
);

const request = <T = any>(
  config: CustomAxiosRequestConfig
): Promise<BaseResponse<T>> => {
  return new Promise((resolve, reject) => {
    service
      .request<BaseResponse<T>>(config)
      .then((res) => resolve(res.data))
      .catch((err) => reject(err));
  });
};

export default request;
